package handler

import (
	"encoding/json"
	"pig-manage/cahce"
	"pig-manage/moder"
	"pig-manage/pkg"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func UserLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"mas":  "不能为空",
			"code": 500,
		})
		return
	}

	redis_key := "redis_login" + username
	errCount, _ := cahce.Rdb.Get(cahce.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"mas":  "密码错误3次",
			"code": 500,
		})
		return
	}

	var user moder.User
	err := moder.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"mas":  "查询失败",
			"code": 500,
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"mas":  "用户名为空",
			"code": 500,
		})
		return
	}

	if user.Password != pkg.MD5(password) {
		cahce.Rdb.Incr(cahce.Ctx, redis_key)
		if errCount == 2 {
			cahce.Rdb.Set(cahce.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"mas":  "密码错误3次，封禁2小时",
				"code": 500,
			})
			return
		}
		c.JSON(200, gin.H{
			"mas":  "密码错误",
			"code": 500,
		})
		return
	}

	c.JSON(200, gin.H{
		"mas":  "密码正确",
		"code": 200,
		"data": user,
	})
	return
}

func RodeNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := moder.RodNode{
		Rid: rid,
		Nid: nid,
	}
	moder.DB.Create(&data)
	c.JSON(200, gin.H{
		"mas":  "成功",
		"code": 200,
		"data": data,
	})
	return

}

func UserRode(c *gin.Context) {
	uid := c.Query("uid")
	/*
		SELECT
		  *
		FROM
		  rodes
		  LEFT JOIN user_rodes ON user_rodes.rid = rodes.id
		WHERE
		  user_rodes.uid =1
	*/
	var data []moder.Rode
	moder.DB.Table("rodes").
		Joins("LEFT JOIN user_rodes ON user_rodes.rid = rodes.id").
		Where("user_rodes.uid = ?", uid).
		Debug().
		Find(&data)
	c.JSON(200, gin.H{
		"mas":  "成功",
		"code": 200,
		"data": data,
	})
	return
}

func RodeNode(c *gin.Context) {
	rid := c.Query("rid")
	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN rod_nodes ON rod_nodes.nid = nodes.id
		WHERE
		  rod_nodes.rid =1
	*/
	var data []moder.Node
	moder.DB.Table("nodes").
		Joins("LEFT JOIN rod_nodes ON rod_nodes.nid = nodes.id").
		Where("rod_nodes.rid =?", rid).
		Debug().
		Find(&data)
	c.JSON(200, gin.H{
		"mas":  "成功",
		"code": 200,
		"data": data,
	})
	return

}

func Goods(c *gin.Context) {
	GoodsNO := c.PostForm("GoodsNO")
	GoodsName := c.PostForm("GoodsName")
	data := moder.Goods{
		GoodsNO:   GoodsNO,
		GoodsName: GoodsName,
	}
	moder.DB.Create(&data)
	c.JSON(200, gin.H{
		"mas":  "成功",
		"code": 200,
		"data": data,
	})
	return
}

func Order(c *gin.Context) {
	OrderNo := c.PostForm("OrderNo")
	OrderName := c.PostForm("OrderName")
	OrderPrice := c.PostForm("OrderPrice")
	Gid, _ := strconv.Atoi(c.PostForm("Gid"))
	data := moder.Order{
		OrderNo:    OrderNo,
		OrderName:  OrderName,
		OrderPrice: OrderPrice,
		Gid:        Gid,
	}

	moder.DB.Create(&data)
	c.JSON(200, gin.H{
		"mas":  "成功",
		"code": 200,
		"data": data,
	})
	return

}

func GoodsOrder(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	if size > 50 {
		c.JSON(200, gin.H{
			"mas":  "size要求小于等于50",
			"code": 500,
		})
		return
	}

	offset := (page - 1) * size

	var data []moder.GoodsOrder
	/*
		SELECT
		  goods.id AS ID,
		  goods.goods_no AS GoodsNO,
		  goods.goods_name AS GoodsName,
		  orders.order_no AS OrderNo,
		  orders.order_name AS OrderName,
		  orders.order_price AS OrderPrice
		FROM
		  goods
		  LEFT JOIN orders ON orders.gid = goods.id
	*/

	redis_key := "redis_list" + strconv.Itoa(page)
	result, _ := cahce.Rdb.Get(cahce.Ctx, redis_key).Result()
	if result == "" {
		moder.DB.Table("goods").
			Select(
				"goods.id AS ID",
				"goods.goods_no AS GoodsNO",
				"goods.goods_name AS GoodsName",
				"orders.order_no AS OrderNo",
				"orders.order_name AS OrderName",
				"orders.order_price AS OrderPrice",
			).
			Joins("LEFT JOIN orders ON orders.gid = goods.id").
			Offset(offset).
			Limit(size).
			Debug().
			Find(&data)
		jsonData, _ := json.Marshal(data)
		cahce.Rdb.Set(cahce.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &data)
	}

	var total int64
	moder.DB.Model(&moder.Order{}).Count(&total)
	c.JSON(200, gin.H{
		"mas":   "成功",
		"code":  200,
		"data":  data,
		"total": total,
	})
	return

}
